<template>
  <div class="renwu-create-container">
    <el-form 
      :model="formInline" 
      :rules="rules" 
      label-position="top" 
      class="demo-form-inline"
      ref="formRef"
    >
      <!-- 年级选择 - 必填项 -->
      <el-form-item 
        label="年级" 
        prop="gradeLevel" 
        required
      >
        <el-select v-model="formInline.gradeLevel" style="width: 300px" clearable placeholder="请选择年级">
          <el-option v-for="item in LevelStore.list" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 标题输入 - 必填项 -->
      <el-form-item 
        label="标题" 
        prop="title" 
        required
      >
        <el-input v-model="formInline.title" placeholder="请输入任务标题" style="width: 100%" />
      </el-form-item>

      <!-- 试卷列表 - 必填项 -->
      <el-form-item 
        label="试卷列表" 
        prop="paperItems" 
        required
      >
        <el-table :data="formInline.paperItems" border style="width: 100%">
          <el-table-column prop="subjectName" label="学科" />
          <el-table-column prop="name" label="试卷名称" />
          <el-table-column prop="createTime" label="创建时间"  />
          <el-table-column fixed="right" label="操作"  align="center">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removePaper(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <div class="action-buttons">
          <el-button type="primary" @click="submitForm">提交任务</el-button>
          <el-button type="success" @click="addPaper">添加试卷</el-button>
          <el-button type="warning" @click="resetForm">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <!-- 添加试卷对话框 -->
    <AddPaperDialog ref="addPaperDialogRef" @addPaper="handleAddPaper" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { useLevelStore } from '@/stores/level';
import { 
  taskSelect, 
  type TaskDetail, 
  type PaperItem, 
  subjectList, 
  type Subject,
  taskEdit, 
  type TaskEditParams,
  type PaperItemForEdit
} from '@/api/renwu';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import AddPaperDialog from './AddPaperDialog.vue';

// 使用仅类型导入语法
import type { FormInstance } from 'element-plus';

const LevelStore = useLevelStore();
const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance | null>(null);

// 定义表单数据接口
interface FormInlineType {
  id?: number; // 任务ID（编辑时存在）
  gradeLevel: number | null;
  title: string;
  paperItems: PaperItem[];
}

// 定义表单初始值
const initialFormState: FormInlineType = {
  gradeLevel: null,
  title: '',
  paperItems: []
};

// 使用接口类型定义formInline
const formInline = reactive<FormInlineType>({...initialFormState});

// 学科列表数据
const subjectListData = ref<Subject[]>([]);

// 表单验证规则
const rules = {
  gradeLevel: [
    { required: true, message: '请选择年级', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  paperItems: [
    { 
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一份试卷'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 提交表单（带验证）
const submitForm = async () => {
  const form = formRef.value;
  if (!form) return;
  
  form.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 确保年级已选择
        if (formInline.gradeLevel === null) {
          ElMessage.error('请选择年级');
          return;
        }
        
        // 确保有试卷
        if (formInline.paperItems.length === 0) {
          ElMessage.error('请至少添加一份试卷');
          return;
        }
        
        // 准备提交数据 - 确保字段正确
        const submitData: TaskEditParams = {
          id: formInline.id, // 任务ID（编辑时存在）
          gradeLevel: formInline.gradeLevel,
          title: formInline.title,
          // 过滤掉前端添加的额外属性
          paperItems: formInline.paperItems.map(item => ({
            id: item.id,
            name: item.name,
            questionCount: item.questionCount,
            score: item.score,
            createTime: item.createTime,
            createUser: item.createUser,
            subjectId: item.subjectId,
            paperType: item.paperType,
            frameTextContentId: item.frameTextContentId // 确保包含此关键字段
          }))
        };

        console.log('提交任务数据:', JSON.stringify(submitData, null, 2));
        
        // 调用任务编辑接口
        const res = await taskEdit(submitData);
        
        if (res.code === 1) {
          ElMessage.success(res.message || '任务提交成功');
          console.log('任务创建/更新结果:', res.response);
          
          // 成功后的处理
          if (route.query.taskId) {
            // 编辑模式：刷新当前数据
            await fetchTaskData();
            ElMessage.success('任务更新成功');
          } else {
            // 新增模式：重置表单并跳转到列表页
            resetForm();
            // 延迟跳转让用户看到成功消息
            setTimeout(() => {
              router.push('/renwu');
            }, 1500);
          }
        } else {
          throw new Error(res.message || '任务提交失败');
        }
      } catch (error: any) {
        console.error('提交失败:', error);
        ElMessage.error(error.message || '任务提交失败，请稍后重试');
      }
    } else {
      ElMessage.error('请完成所有必填项');
    }
  });
};

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const res = await subjectList();
    if (res.code === 1 && res.response) {
      subjectListData.value = res.response;
    } else {
      ElMessage.error(res.message || '获取学科列表失败');
    }
  } catch (error) {
    console.error('获取学科列表时出错:', error);
    ElMessage.error('获取学科列表失败，请稍后重试');
  }
};

// 根据学科ID获取学科名称
const getSubjectName = (subjectId: number): string => {
  const subject = subjectListData.value.find(s => s.id === subjectId);
  return subject ? subject.name : `学科${subjectId}`;
};

// 根据路由ID获取任务详情
const fetchTaskData = async () => {
  const taskId = route.query.taskId;
  if (taskId && typeof taskId === 'string') {
    try {
      const res = await taskSelect(parseInt(taskId));
      if (res.code === 1 && res.response) {
        const taskDetail = res.response;
        
        // 填充表单数据
        formInline.id = taskDetail.id; // 确保设置ID
        formInline.gradeLevel = taskDetail.gradeLevel;
        formInline.title = taskDetail.title;
        
        // 处理试卷数据 - 确保包含 frameTextContentId
        formInline.paperItems = taskDetail.paperItems.map(item => ({
          ...item,
          subjectName: getSubjectName(item.subjectId)
        }));
      } else {
        ElMessage.error(res.message || '获取任务信息失败');
      }
    } catch (error) {
      console.error('获取任务信息时出错:', error);
      ElMessage.error('获取任务信息失败，请稍后重试');
    }
  } else {
    // 新增模式，重置ID
    formInline.id = undefined;
  }
};

// 处理添加试卷事件
const handleAddPaper = (papers: PaperItem[]) => {
  papers.forEach(paper => {
    const exists = formInline.paperItems.some(item => item.id === paper.id);
    if (!exists) {
      // 设置学科名称
      paper.subjectName = getSubjectName(paper.subjectId);
      formInline.paperItems.push(paper);
    }
  });
  
  ElMessage.success(`成功添加 ${papers.length} 份试卷`);
};

// 删除试卷
const removePaper = (index: number) => {
  formInline.paperItems.splice(index, 1);
  ElMessage.success('试卷已移除');
};

// 重置表单
const resetForm = () => {
  Object.assign(formInline, initialFormState);
  ElMessage.success('表单已重置');
};

const addPaperDialogRef = ref<InstanceType<typeof AddPaperDialog>>();

// 添加一个方法来打开对话框
const addPaper = () => {
  if (addPaperDialogRef.value) {
    addPaperDialogRef.value.openDialog();
  } else {
    console.error('对话框引用未定义');
  }
};

onMounted(async () => {
  await fetchSubjectList();
  fetchTaskData();
});
</script>

<style scoped>
.renwu-create-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0; /* 移除容器内边距 */
  background: transparent; /* 透明背景 */
}

.demo-form-inline {
  padding: 20px;
  background: #fff; /* 表单背景色 */
  border-radius: 8px; /* 保留表单圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-form-item label {
  font-weight: bold;
  color: #606266;
  margin-bottom: 8px;
  display: block;
}

.el-table {
  margin-top: 10px;
  border-radius: 4px;
  overflow: hidden;
}

.el-table :deep(.cell) {
  padding: 12px 0;
}
</style>